package com.winit.openapi.sms;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.BpartnerService;
import com.winit.erp.spi.bpartner.command.BpartnerCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.mms.spi.common.Constant;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.sms.common.SmsUtils;
import com.winit.openapi.sms.validator.AdvanceFieldValidator;
import com.winit.openapi.sms.validator.SellerAdvanceFieldValidator;
import com.winit.sms.spi.wallet.onlinerecharge.OnLineRechargeService;
import com.winit.sms.spi.wallet.onlinerecharge.command.QueryOnLineRechargeByAdvanceNameCommand;
import com.winit.sms.spi.wallet.selleradvance.AdvanceSevice;
import com.winit.sms.spi.wallet.selleradvance.OrgConfigService;
import com.winit.sms.spi.wallet.selleradvance.SellerAdvanceService;
import com.winit.sms.spi.wallet.selleradvance.command.CreateAdvanceCommand;
import com.winit.sms.spi.wallet.selleradvance.command.ModifySellerAdvanceCommand;
import com.winit.sms.spi.wallet.selleradvance.command.OrgConfigCommand;
import com.winit.sms.spi.wallet.selleradvance.command.QueryAdVanceCommand;
import com.winit.sms.spi.wallet.selleradvance.vo.AdvanceVo;
import com.winit.sms.spi.wallet.selleradvance.vo.OrgConfigVo;

/**
 * 代付人controller
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * sheng.huang 	1.0  		2016年3月22日 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/sms/advance")
public class AdvanceController extends BaseController {

    private static Logger         logger = LoggerFactory.getLogger(AdvanceController.class);
    @Resource
    private AdvanceSevice         advanceSevice;
    @Resource
    private OnLineRechargeService onLineRechargeService;
    @Resource
    private BpartnerService       bpartnerService;
    @Resource
    private OrgConfigService      orgConfigService;
    @Resource
    private SellerAdvanceService  sellerAdvanceService;
    

    /**
     * TODO 根据传入的JSON参数创建代付人信息
     * 
     * @param requestMsg 传入的参数
     * @param responseMsg 传出的参数
     * @return
     */
    @RequestMapping("/createAdvance")
    public String createAdvance(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        if (null == getCustomerCode()) {
            return ERROR;
        }
        SellerAdvanceFieldValidator.validCreateAdvance(SmsUtils.toJsonObject(requestMsg.getData()), "list");
        List<CreateAdvanceCommand> commands = SmsUtils.getObjectList(requestMsg.getData(),
            CreateAdvanceCommand.class,
            "list");
        StringBuffer result = new StringBuffer();
        //        Set<String> set = new HashSet<String>();
        QueryAdVanceCommand command = new QueryAdVanceCommand();
        command.setCustomerCode(getCustomerCode());
        for (CreateAdvanceCommand c : commands) {
            command.setAdvanceType(c.getAdvanceType());
            command.setAdvanceName(c.getAdvanceName());
            c.setCtx(CommandContext.getContext());
            c.setCustomerCode(getCustomerCode());
            List<AdvanceVo> personList = advanceSevice.getAdvanceVoList(command);
            if (CollectionUtils.isEmpty(personList)) {
                continue;
            }
            for (AdvanceVo advanceVo : personList) {
                if (StringUtils.isNotBlank(advanceVo.getAdvanceName())) {
                    result.append(advanceVo.getAdvanceName()).append(",");
                }
            }

            //            CommandContext ctx = CommandContext.getContext();
            //            c.setCtx(ctx);
            //            c.setCustomerCode(getCustomerCode());
            //            if ("true".equals(c.getIsAddSource())) {
            //                c.setCreateAdvanceDate(new Date());
            //            }
            // 如果客户编码和代付人名称相同，则记录相同的代付人名称返回给OPC
            //            if (!set.add(c.getCustomerCode() + c.getAdvanceName())) {
            //                result.append(c.getAdvanceName()).append(",");
            //            }
        }
        if (StringUtils.isNotBlank(result.toString())) {
            String string = result.toString().substring(0, result.toString().length() - 1);
            responseMsg.setCode(ErrorCode.ADVANCE_NAME_EXIST);
            responseMsg.setMsg("存在相同的代付人:" + string);
            return ERROR;
        }
        Long advanceId = advanceSevice.createAdvance(commands, getCustomerCode());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("advanceId", advanceId);
        responseMsg.setData(map);
        return SUCCESS;
    }

    /**
     * 根据类型查询代付人列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryAdvanceList")
    public String getAdvaceList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        if (null == getCustomerCode()) {
            return ERROR;
        }
        QueryAdVanceCommand command = new QueryAdVanceCommand();
        command.setCtx(CommandContext.getContext());
        command.setCustomerCode(getCustomerCode());
        command.setAdvanceType("PERSON");
        List<AdvanceVo> personList = advanceSevice.getAdvanceVoList(command);
        command.setAdvanceType("COMPANY");
        List<AdvanceVo> companyList = advanceSevice.getAdvanceVoList(command);
        //最近一次代付人
        QueryOnLineRechargeByAdvanceNameCommand queryOnLineRechargeByAdvanceNameCommand = new QueryOnLineRechargeByAdvanceNameCommand();
        queryOnLineRechargeByAdvanceNameCommand.setCustomerCode(command.getCustomerCode());
        String advanceName = onLineRechargeService.queryLastAdvanceByCustomerCode(queryOnLineRechargeByAdvanceNameCommand);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("personList", personList);
        map.put("companyList", companyList);
        map.put("advanceName", advanceName);
        responseMsg.setData(map);
        logger.info("登录查询代付人信息结束");
        return SUCCESS;
    }

    /**
     * 根据类型、代付人和客户编码删除代付人信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/removeAdvanceByCode")
    public String removeAdvanceByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	try {
        	QueryAdVanceCommand queryAdVanceCommand = JSON.parseObject(requestMsg.getData().toString(), QueryAdVanceCommand.class);
        	AdvanceFieldValidator.validRemoveField(SmsUtils.toJsonObject(requestMsg.getData()));
            queryAdVanceCommand.setCustomerCode(getCustomerCode());
            //逻辑删除
            advanceSevice.removeAdvanceByCode(queryAdVanceCommand);
            
            ModifySellerAdvanceCommand modifyCommand = new ModifySellerAdvanceCommand();
            modifyCommand.setAdvanceName(queryAdVanceCommand.getAdvanceName());
            modifyCommand.setCustomerCode(getCustomerCode());
            modifyCommand.setIsDelete(SmsUtils.STATUS_Y);
            sellerAdvanceService.modifySellerAdvance(modifyCommand);
		} catch (SPIException e) {
			logger.error(e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            return ERROR;
		}
        return SUCCESS;
    }

    /**
     * 查询代付拦截列表数据
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/queryAdvanceData")
    public String queryAdvanceData(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	BpartnerCommand command = new BpartnerCommand();
    	CommandContext ctx = CommandContext.getContext();
    	Long cBpartnerId = Long.parseLong(ctx.getUserId());
    	command.setcBpartnerId(cBpartnerId);
    	Bpartner bpartner = bpartnerService.queryBpartnerById(command);
    	if(null != bpartner){
    		Map<String, Object> data = new HashMap<String, Object>();	//返回map
    		//根据客户编码查询代付拦截列表数据
    		QueryAdVanceCommand qcommand = new QueryAdVanceCommand();
    		qcommand.setCustomerCode(bpartner.getValue());
    		List<AdvanceVo> aList = advanceSevice.getAdvanceVoListByLogin(qcommand);
    		
    		//查询组织是否需要代付
    		OrgConfigCommand oCommand = new OrgConfigCommand();
    		oCommand.setOrgId(CommandContext.getContext().getOrgId()+"");
            oCommand.setCtx(CommandContext.getContext());
    		List<OrgConfigVo> oList = orgConfigService.queryOrgConfigEntityList(oCommand);
    		boolean advanceFlag = true;
            if (oList != null && oList.size() > 0) {
                OrgConfigVo vo = oList.get(0);
                if (Constant.NOT_ACTIVE.equals(vo.getAdvanceFlag())) {
                    advanceFlag = false;
                }
            }
            data.put("advanceFlag", advanceFlag);//是否显示代付协议
            data.put("advanceList", aList);//代付拦截列表数据
            responseMsg.setData(data);
    	}
    	return SUCCESS;
    }
    
    /**
     * 根据上下文获取客户编码
     * 
     * @return
     */
    private String getCustomerCode() {
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>根据客户id:{}查询客户code为空");
            return null;
        }
        return bpartner.getValue();
    }
}
